<?php
class DataBaseClass{
	private $dbChaveReferencia = ""; //CHAVE QUE IDENTIFICA OS OBJETOS QUE COMPARTILHAM A MESMA CONEX�O

	private $dbConnection = null;
	private $dbHost = "";
	private $dbUser = "multinet_user";
	private $dbPassword = "sgsc0210";
	private $dbName = "multinet_alcateiaws";

	private $error_code = 0;
	private $error_state = 0;
	private $error_message = "";

	public $refdir = ""; //INCLUIDO POR MARCELO RAMOS EM 17/05/2010
	public $SCRIPT_NAME = "";

	private $aIniFile = Array();

	private $info="";
	private $line="";
	private $file="";
	private $tempoExec = "";
	private $function="";

	private $DS;
	private $log = true;

	public function __construct($host="",$user="",$pass="",$db_name="",$driver='mysql'){
		$path_root_dbClass = dirname(__FILE__);
		$this->DS = DIRECTORY_SEPARATOR;
		$path_root_dbClass="{$path_root_dbClass}{$this->DS}";
		$this->refdir = $path_root_dbClass;

		$host=($host=="")?$this->dbHost:$host;
		$user=($user=="")?$this->dbUser:$user;
		$pass=($pass=="")?$this->dbPassword:$pass;
		$db_name=($db_name=="")?$this->dbName:$db_name;

		$this->dbConnection = mysql_connect($host, $user, $pass);
		mysql_select_db($db_name,$this->dbConnection);
		$this->referenciarDir();
		// testando a conex�o
		if (!$this->dbConnection) {
			printf("Falha na conex�o: %s\n", mysql_connect_error());
			exit();
		}
		$this->dbChaveReferencia = $this->dbCriarChave();
		//$this->db_execute("SET NAMES 'utf8' COLLATE 'utf8_general_ci'");

	} // METODO CONSTRUTOR
	
	public function getDbHost() {
		return $this->dbHost;
	}

	public function getDbUser() {
		return $this->dbUser;
	}

	public function getDbPassword() {
		return $this->dbPassword;
	}

	public function getDbName() {
		return $this->dbName;
	}

 
	public function utf8Encode2Decode($string)
	{
		/*if(mb_detect_encoding($string."x", 'UTF-8, ISO-8859-1') == 'UTF-8'){
			return $string;
		}else{
			return utf8_encode($string);
		}*/
		return $string;
	}

	public function utf8_array_encode($input) {
		$return = array();
		foreach ($input as $key => $val) {
			if (is_array($val)) {
				$return[$key] = $this->utf8_array_encode($val);
			} else {
				$return[$key] = $this->utf8Encode2Decode($val);
			}
		}
		return $return;
	}

	public function setErrorCode($code){
		$this->error_code = $code;
	}//MÉTODO setErrorCode

	public function setErrorState($state){
		$this->error_state = $state;
	}//MÉTODO setErrorState

	public function setErrorMessage($message){
		$this->error_message = $message;
	}//MÉTODO setErrorMessage

	public function getErrorCode(){
		return ($this->error_code!=0) ? $this->error_code : 0;
	}//MÉTODO getErrorCode

	public function getErrorState(){
		return ($this->error_state!=0) ? $this->error_state : 0;
	}//MÉTODO getErrorState

	public function getErrorMessage(){
		return ($this->error_message!='') ? $this->error_message : '';
	}//MÉTODO getErrorMessage

	public function getFullError(){
		$aErro = Array(
			'code' => 0,
			'state' => 0,
			'message' => ''
		);
		$aErro['code']=$this->getErrorCode();
		$aErro['state']=$this->getErrorState();
		$aErro['message']=$this->getErrorMessage();
		return $aErro;
	}
	
	public function dbCriarChave(){
		/*
		** METODO QUE CRIA UMA CHAVE DE IDENTIFICA��O QUE � PASSADA AO OBJETO
		*/
		$strChave = "";
		$signos = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
		$tamanho_chave = rand(4,20);
		for($x = 0; $x < $tamanho_chave; $x++){
			$randIndice = rand(0, strlen($signos));
			$strChave .= $signos[$randIndice];
		}

		return $strChave;
	} //MÉTODO dbCriarChave

	public function getChave(){
		return $this->dbChaveReferencia;
	}

	public function db_log($fileName, $sql, $status, $total=null, $message=null){

		
		if(!is_dir("{$this->refdir}log")){
			@mkdir("{$this->refdir}log",0777);
		}
		@chmod("{$this->refdir}log", 0777);
		$fileName = "{$this->refdir}log{$this->DS}dblog" . "_" . date("YmdHi") . ".txt";
		/*print_r($fileName);
		die();*/
		//echo "<pre>",print_r($fileName,true)."</pre>";
		$datetimeLog = date("d/m/Y H:i:s");
		$sql = trim($sql);
		$msg = array();
		$msg[] = "*************************************************************************************";
		$msg[] = $this->utf8Encode2Decode("Data: {$datetimeLog}");
		$msg[] = $this->utf8Encode2Decode("Arquivo: {$this->file} [{$this->line}]");
		$msg[] = $this->utf8Encode2Decode("Função: {$this->function}");
		$msg[] = $this->utf8Encode2Decode("Query: {$sql}");
		$msg[] = $this->utf8Encode2Decode("Resultado: [{$total}] Registros ");
		$msg[] = $this->utf8Encode2Decode("{$status} {$message}");
		$msg[] = $this->utf8Encode2Decode("Tempo de execução: {$this->tempoExec}");
		$msg[] = "\n";
		if($this->log==true){
			file_put_contents($fileName, implode("\r\n",$msg), FILE_APPEND);
			@chmod($fileName, 0777);
		}
		$this->file = "";
		$this->line = "";
		$this->function = "";
		$this->tempoExec = "0.000001";
	}

	//fun��es de banco de dados
	public function db_query($sql){
		$query_time = microtime(true);
		$result = array(
			'success' => false,
			'result' => null,
			'total' => 0,
			'message' => ''
		);

		$qry = mysql_query($sql,$this->dbConnection);

		$this->tempoExec = number_format(microtime(true) - $query_time, 4)." segundos";
		$this->info = debug_backtrace();
		$this->line = $this->info[0]['line'];
		$this->file = $this->info[0]['file'];
		if(array_key_exists('class',$this->info[0])) {
			$this->function = "{$this->info[1]['class']}{$this->info[1]['type']}{$this->info[1]['function']}";
			if(is_array($this->info[1]['args']) && count($this->info[1]['args']) > 0){
				if(!is_object($this->info[1]['args'][0])){
					if(is_array($this->info[1]['args'])){
						$this->function .= "(".implode(',',$this->info[1]['args']).")";
					}else{
						$this->function .= "({$this->info[1]['args']})";
					}
				}else{
					$this->function .= "()";
				}
			}
		}else {
			$this->function = $this->info[1]['function'];
			if(count($this->info[1]['args']) > 0){
				if(!is_object($this->info[1]['args'][0])){
					$this->function .= "(".implode(',',$this->info[1]['args']).")";
				}else{
					$this->function .= "()";
				}
			}
		}

		if($qry==true) {
			$result['success'] = true;
			$result['result'] = $qry;
			$result['message'] = '';
			$result['total'] = $this->db_num_rows($qry);

			$this->db_log('../../log/dblog.txt', $sql, 'Query executada com sucesso', $result['total'], $result['message']);

		} else{
			$result['success'] = false;
			$result['message'] = $this->db_error();
			$result['result'] = array();
			$result['total'] = 0;

			$this->db_log('../../log/dblog.txt', $sql, 'Erro executando query', 0, $result['message']);

		}

		return $result;

	}

	//fun��es de banco de dados
	public function db_proc_query($sql){
		$query_time = microtime(true);
		$result = array(
			'success' => false,
			'result' => null,
			'total' => 0,
			'message' => ''
		);
		$ret = array();
		if (mysql_multi_query($this->dbConnection, $sql)) {
			$this->tempoExec = number_format(microtime(true) - $query_time, 4)." segundos";
			$this->info = debug_backtrace();
			$this->line = $this->info[0]['line'];
			$this->file = $this->info[0]['file'];
			if(array_key_exists('class',$this->info[0])) {
				$this->function = "{$this->info[1]['class']}{$this->info[1]['type']}{$this->info[1]['function']}";
				if(count($this->info[1]['args']) > 0){
					if(!is_object($this->info[1]['args'][0])){
						$this->function .= "(".implode(',',$this->info[1]['args']).")";
					}else{
						$this->function .= "()";
					}
				}
			}else {
				$this->function = $this->info[1]['function'];
				if(count($this->info[1]['args']) > 0){
					if(!is_object($this->info[1]['args'][0])){
						$this->function .= "(".implode(',',$this->info[1]['args']).")";
					}else{
						$this->function .= "()";
					}
				}
			}
			do {
				/* store first result set */
				if ($result = mysql_store_result($this->dbConnection)) {
					while ($row = mysql_fetch_assoc($result)) {
						array_push($ret,$row);
					}
					mysql_free_result($result);
				}
			} while (mysql_next_result($this->dbConnection));
			$this->db_log('../../log/dblog.txt', $sql, 'Query executada com sucesso', $result['total'], $result['message']);
			$result['result'] = $ret;
			$result['success'] = true;
			$result['total'] = count($ret);
		}else{
			$result['success'] = false;
			$result['message'] = $this->db_error();
			$result['result'] = array();
			$result['total'] = 0;
			$this->db_log('../../log/dblog.txt', $sql, 'Erro executando query', 0, $result['message']);
		}

		return $result;

	}

	//fun��es de banco de dados
	public function db_execute($sql){
		$query_time = microtime(true);
		$result = array(
			'success' => false,
			'result' => array(),
			'total' => 0,
			'message' => '',
			'last_id' => 0
		);
		$qry = mysql_query($sql,$this->dbConnection);
		$this->tempoExec = number_format(microtime(true) - $query_time, 4)." segundos";
		$this->info = debug_backtrace();
		$this->line = $this->info[0]['line'];
		$this->file = $this->info[0]['file'];
		if(array_key_exists('class',$this->info[0])) {
			$this->function = "{$this->info[1]['class']}{$this->info[1]['type']}{$this->info[1]['function']}";
			if(count($this->info[1]['args']) > 0){
				if(!is_object($this->info[1]['args'][0])){
					$this->function .= "(".implode(',',$this->info[1]['args']).")";
				}else{
					$this->function .= "()";
				}
			}
		}else {
			$this->function = $this->info[1]['function'];
			if(count($this->info[1]['args']) > 0){
				if(!is_object($this->info[1]['args'][0])){
					$this->function .= "(".implode(',',$this->info[1]['args']).")";
				}else{
					$this->function .= "()";
				}
			}
		}

		if ($qry) {

			$tmp = trim(strtoupper($sql));
			$aTmp = explode(" ",$tmp);
			
			if($aTmp!="DELETE"){
				$id = $this->db_last_insert_id();
			}else{
				$id=0;
			}
			$result['success'] = true;
			$result['message'] = '';
			$result['total'] = $this->db_affected_rows();
			$result['last_id'] = $id;
			
			$this->db_log('../../log/dblog.txt', $sql, 'Query executada com sucesso', $result['total'], $result['message']);
		} else{
			
			$result['success'] = false;
			$result['message'] =  $this->db_error();
			$result['total'] = 0;
			$result['last_id'] = 0;

			$this->db_log('../../log/dblog.txt', $sql, 'Erro executando query', 0, $result['message']);
		}

		return $result;
	}

	public function db_last_insert_id(){
		return mysql_insert_id($this->dbConnection);
	}

	public function db_autocommit($opt){
		return $this->dbConnection->autocommit($opt);
	}

	public function db_start_transaction(){
		$sql = "START TRANSACTION";
		mysql_query("SET AUTOCOMMIT=0",$this->dbConnection);
		$this->db_log('../../log/dblog.txt', 'START TRANSACTION', 'Query executada com sucesso', 1, '');
		return mysql_query($sql,$this->dbConnection);
	}

	public function db_commit(){
		$sql = "COMMIT";
		$this->db_log('../../log/dblog.txt', 'COMMIT', 'Query executada com sucesso', 1, '');
		return mysql_query($sql,$this->dbConnection);
	}

	public function db_rollback(){
		$sql = "ROLLBACK";
		$this->db_log('../../log/dblog.txt', 'ROLLBACK', 'Query executada com sucesso', 1, '');
		return mysql_query($sql,$this->dbConnection);
	}

	public function db_error(){

		$this->setErrorCode($this->dbConnection->errno);
		$this->setErrorState($this->dbConnection->sqlstate);
		$this->setErrorMessage($this->dbConnection->error);

		$erro = 'Code: ' . $this->dbConnection->errno;
		$erro .= '  / State: ' . $this->dbConnection->sqlstate;
		$erro .= '<br/>Message: ' . $this->dbConnection->error;
		//tratando a virgula para evitar erro no json_encode!
		$erro = str_replace(',',' ',$erro);
		return trim($erro);
	}

	public function db_escape_string($value){
		return mysql_real_escape_string($value,$this->dbConnection);
	}

	public function db_fetch_assoc($result){
		return mysql_fetch_assoc($result);
	}

	public function db_fetch_array($result){
		return mysql_fetch_array($result);
	}

	public function db_fetch_row($result){
		return mysql_fetch_row($result);
	}

	public function db_num_rows($result){
		return mysql_num_rows($result);
	}

	public function db_fetch_object($result){
		return mysql_fetch_object($result);
	}

	public function db_free_result($result){
		mysql_free_result($result);
	}

	public function db_affected_rows(){
		return mysql_affected_rows($this->dbConnection);
	}

	public function db_close(){
		mysql_close($this->dbConnection);
	}

	public function referenciarDir(){
		$caminho = $_SERVER["SCRIPT_NAME"];
		$caminho = preg_replace("/^\/?[_a-zA-Z0-9]+\/?/", "", $caminho);
		$this->SCRIPT_NAME = $caminho;
		$caminho = preg_replace("/([_a-zA-Z0-9]+)*(\.[a-z]+)+$/", "", $caminho);
		$caminho = preg_replace("/[a-zA-Z0-9]+(_?[a-zA-Z0-9]+)*\//", "../", $caminho);
		$this->refdir = $caminho;
		if(!is_file($this->refdir . 'php_library/functions.php')){
			$path_root_cja = dirname(__FILE__);
			$DS = DIRECTORY_SEPARATOR;
			$this->refdir = "{$path_root_cja}{$DS}..{$DS}";
		}
	} //MÉTODO referenciarDir
	
	

	public function array_escape_string($input) {
		$return = array();
		foreach ($input as $key => $val) {
			if (is_array($val)) {
				$return[$key] = $this->array_escape_string($val);
			} else {
				$return[$key] = $this->db_escape_string($val);
			}
		}
		return $return;
	}

}
